package com.xdw.vuebackdemo.controller.test;

import com.xdw.vuebackdemo.base.common.ApiResult;
import com.xdw.vuebackdemo.base.storage.StorageFactory;
import com.xdw.vuebackdemo.config.SiteOptions;
import com.xdw.vuebackdemo.constant.Constant;
import com.xdw.vuebackdemo.util.FileKit;
import com.xdw.vuebackdemo.vo.UploadFile;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * Ueditor 文件上传
 *
 * @author langhsu
 */
@RestController
@RequestMapping("/test")
public class UploadController {
    private Logger logger = LoggerFactory.getLogger(UploadController.class);
    public static HashMap<String, String> errorInfo = new HashMap<>();
    @Autowired
    protected StorageFactory storageFactory;
    @Autowired
    protected SiteOptions siteOptions;
    static {
        errorInfo.put("SUCCESS", "SUCCESS"); //默认成功
        errorInfo.put("NOFILE", "未包含文件上传域");
        errorInfo.put("TYPE", "不允许的文件格式");
        errorInfo.put("SIZE", "文件大小超出限制，最大支持2Mb");
        errorInfo.put("ENTYPE", "请求类型ENTYPE错误");
        errorInfo.put("REQUEST", "上传请求异常");
        errorInfo.put("IO", "IO异常");
        errorInfo.put("DIR", "目录创建失败");
        errorInfo.put("UNKNOWN", "未知错误");
    }

    @ApiOperation(value = "图片上传测试接口", notes="图片上传")
    @PostMapping("/upload")
    public ApiResult upload(@RequestParam(value = "file", required = false) MultipartFile file,
                               HttpServletRequest request) {
        String crop = request.getParameter("crop");
        int size = ServletRequestUtils.getIntParameter(request, "size", siteOptions.getIntegerValue(Constant.STORAGE_MAX_WIDTH));

        // 检查空
        if (null == file || file.isEmpty()) {
            return ApiResult.failure(errorInfo.get("NOFILE"));
        }

        String fileName = file.getOriginalFilename();

        // 检查类型
        if (!FileKit.checkFileType(fileName)) {
            return ApiResult.failure(errorInfo.get("TYPE"));
        }

        // 检查大小
        String limitSize = siteOptions.getValue(Constant.STORAGE_LIMIT_SIZE);
        if (StringUtils.isBlank(limitSize)) {
            limitSize = "2";
        }
        if (file.getSize() > (Long.parseLong(limitSize) * 1024 * 1024)) {
            return ApiResult.failure(errorInfo.get("SIZE"));
        }

        // 保存图片
        try {
            String path;
            if (StringUtils.isNotBlank(crop)) {
                Integer[] imageSize = siteOptions.getIntegerArrayValue(crop, Constant.SEPARATOR_X);
                int width = ServletRequestUtils.getIntParameter(request, "width", imageSize[0]);
                int height = ServletRequestUtils.getIntParameter(request, "height", imageSize[1]);
                path = storageFactory.get().storeScale(file, Constant.thumbnailPath, width, height);
            } else {
                path = storageFactory.get().storeScale(file, Constant.thumbnailPath, size);
            }

            UploadFile uploadFile = new UploadFile();
            uploadFile.setName(fileName);
            uploadFile.setPath(path);
            uploadFile.setSize(file.getSize());
            return ApiResult.success(uploadFile);

        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return ApiResult.failure(errorInfo.get("UNKNOWN"));
        }

    }

}
